var format = require('date-fns/format')
var locale = require('date-fns/locale/zh_cn')

function parse_form(template, fields) {
    //正则  radios|checkboxs|select 匹配的边界 |--|  因为当使用 {} 时js报错
    var preg = /(\|-<span(((?!<span).)*leipiplugins=\"(radios|checkboxs|select)\".*?)>(.*?)<\/span>-\||<(img|input|textarea|select).*?(<\/select>|<\/textarea>|\/>))/gi, preg_attr = /(\w+)=\"(.?|.+?)\"/gi, preg_group = /<input.*?\/>/gi;
    if (!fields) fields = 0;

    var template_parse = template;
    var template_data = [];
    var add_fields = {};
    var checkboxs = 0;

    var pno = 0;
    template.replace(preg, function (plugin, p1, p2, p3, p4, p5, p6) {
        var parse_attr = [];
        var attr_arr_all = {};
        var name = '';
        var select_dot = '';
        var is_new = false;
        var p0 = plugin;
        var tag = p6 ? p6 : p4;
        //alert(tag + " \n- t1 - "+p1 +" \n-2- " +p2+" \n-3- " +p3+" \n-4- " +p4+" \n-5- " +p5+" \n-6- " +p6);

        if (tag == 'radios' || tag == 'checkboxs') {
            plugin = p2;
        } else if (tag == 'select') {
            plugin = plugin.replace('|-', '');
            plugin = plugin.replace('-|', '');
        }
        plugin.replace(preg_attr, function (str0, attr, val) {
            if (attr == 'name') {
                if (val == 'leipiNewField') {
                    is_new = true;
                    fields++;
                    val = 'data_' + fields;
                }
                name = val;
            }

            if (tag == 'select' && attr == 'value') {
                if (!attr_arr_all[attr]) attr_arr_all[attr] = '';
                attr_arr_all[attr] += select_dot + val;
                select_dot = ',';
            } else {
                attr_arr_all[attr] = val;
            }
            var oField = {};
            oField[attr] = val;
            parse_attr.push(oField);
        })
        /*alert(JSON.stringify(parse_attr));return;*/
        if (tag == 'checkboxs') { /*复选组  多个字段 */
            plugin = p0;
            plugin = plugin.replace('|-', '');
            plugin = plugin.replace('-|', '');
            var name = 'checkboxs_' + checkboxs;
            attr_arr_all['parse_name'] = name;
            attr_arr_all['name'] = '';
            attr_arr_all['value'] = '';

            attr_arr_all['content'] = `<span leipiplugins="checkboxs"  title="${attr_arr_all['title']}">`;
            var dot_name = '';
            var dot_value = '';
            p5.replace(preg_group, function (parse_group) {
                var is_new = false;
                var option = {};
                parse_group.replace(preg_attr, function (str0, k, val) {
                    if (k == 'name') {
                        if (val == 'leipiNewField') {
                            is_new = true;
                            fields++;
                            val = 'data_' + fields;
                        }

                        attr_arr_all['name'] += dot_name + val;
                        dot_name = ',';

                    }
                    else if (k == 'value') {
                        attr_arr_all['value'] += dot_value + val;
                        dot_value = ',';
                    }
                    option[k] = val;
                });

                if (!attr_arr_all['options']) attr_arr_all['options'] = [];
                attr_arr_all['options'].push(option);
                //if(!option['checked']) option['checked'] = '';
                var checked = option['checked'] != undefined ? 'checked="checked"' : '';
                attr_arr_all['content'] += `<input type="checkbox" name="${option['name']}" value="${option['value']}"  ${checked}/>${option['value']}&nbsp;`;

                if (is_new) {
                    var arr = {};
                    arr['name'] = option['name'];
                    arr['leipiplugins'] = attr_arr_all['leipiplugins'];
                    add_fields[option['name']] = arr;

                }
            });
            attr_arr_all['content'] += '</span>';

            //parse
            template = template.replace(plugin, attr_arr_all['content']);
            template_parse = template_parse.replace(plugin, `{${name}}`);
            template_parse = template_parse.replace('{|-', '');
            template_parse = template_parse.replace('-|}', '');
            template_data[pno] = attr_arr_all;
            checkboxs++;

        } else if (name) {
            if (tag == 'radios') { /*单选组  一个字段*/
                plugin = p0;
                plugin = plugin.replace('|-', '');
                plugin = plugin.replace('-|', '');
                attr_arr_all['value'] = '';
                attr_arr_all['content'] = `<span leipiplugins="radios" name="${attr_arr_all['name'] }" title="${attr_arr_all['title']}">`;
                var dot = '';
                p5.replace(preg_group, function (parse_group) {
                    var option = {};
                    parse_group.replace(preg_attr, function (str0, k, val) {
                        if (k == 'value') {
                            attr_arr_all['value'] += dot + val;
                            dot = ',';
                        }
                        option[k] = val;
                    });
                    option['name'] = attr_arr_all['name'];
                    if (!attr_arr_all['options']) attr_arr_all['options'] = [];
                    attr_arr_all['options'].push(option);
                    //if(!option['checked']) option['checked'] = '';
                    var checked = option['checked'] != undefined ? 'checked="checked"' : '';
                    attr_arr_all['content'] += `<input type="radio" name="${attr_arr_all['name']}" value="${option['value']}"  ${checked }/>${option['value']}&nbsp;`;

                });
                attr_arr_all['content'] += '</span>';

            } else {
                attr_arr_all['content'] = is_new ? plugin.replace(/leipiNewField/, name) : plugin;
            }
            //attr_arr_all['itemid'] = fields;
            //attr_arr_all['tag'] = tag;
            template = template.replace(plugin, attr_arr_all['content']);
            template_parse = template_parse.replace(plugin, `{${name}}`);
            template_parse = template_parse.replace('{|-', '');
            template_parse = template_parse.replace('-|}', '');
            if (is_new) {
                var arr = {};
                arr['name'] = name;
                arr['leipiplugins'] = attr_arr_all['leipiplugins'];
                add_fields[arr['name']] = arr;
            }
            template_data[pno] = attr_arr_all;


        }
        pno++;
    })
    var parse_form = new Object({
        'fields': fields,//总字段数
        'template': template,//完整html
        'parse': template_parse,//控件替换为{data_1}的html
        'data': template_data,//控件属性
        'add_fields': add_fields//新增控件
    });
    return parse_form;
}

// convert html combining content and data
function unparse_form(form, form_data, controller) {
    let tpl_data = form.data;
    let tpl = form.parse;

    tpl_data.forEach((value, key) => {

        let temp_html = '';
        value['value'] = form_data[value['name']] ? form_data[value['name']] : value['value'];//通用

        switch (value['leipiplugins']) {
            case 'text':
                temp_html = `<input type="text" value="${value['value']}"  name="${value['name']}"  style="${value['style']}"/>`;
                break;
            case 'upload':
                if (controller.action == 'edit') {
                    temp_html = `<input type="hidden" name="${value['name']}" value="${value['value']}" /><input type="file" ${value['orgmulti']=='1'?'multiple':''} input_name="${value['name']}" class="upload"  style="${value['style']}"/><span id="${value['name']}_value"></span>`;
                }
                if (controller.action != 'edit' && value['value']) {
                    let files = value['value'].split(';')
                    files.forEach(file => {
                        temp_html += `<span>${file} <a href="${file}">下载</a><span><br/>`;
                    })
                }
                break;
            case 'textarea':
                temp_html = `<textarea  name="${value['name']}" id="${value['name']}" value="${value['value']}" style="${value['style']}">`;
                temp_html += value['value'];
                temp_html += '</textarea>';
                if (parseInt(value['orgrich']) > 0) {
                    temp_html += '<script>' +
                        `UE.getEditor("${value['name']}",{`
                        + 'toolbars:[['
                        + '"fullscreen", "source", "|","bold", "italic", "underline","|", "justifyleft", "justifycenter", "justifyright", "justifyjustify"]],wordCount:false,elementPathEnabled:false'
                        + ' });</script>';
                }
                break;
            case 'radios':
                temp_html = '';
                value['options'].forEach(item => {
                    var checked = '';
                    if (form_data[value['name']])//原 默认值
                    {
                        checked = form_data[value['name']] == item['value'] ? 'checked="checked"' : '';
                    } else if (item['checked'])//判断isset 就可以,在ie中，checked的值是空的
                    {
                        checked = 'checked="checked"';
                    }
                    temp_html += `<input type="radio" name="${value['name']}" value="${item['value']}" ${checked}>${item['value']}&nbsp;`;
                })
                break;
            case 'checkboxs':
                temp_html = '';

                value['options'].forEach(item => {
                    var checked = '';
                    if (form_data[item['name']]) {//原 默认值
                        checked = form_data[item['name']] > 0 ? 'checked="checked"' : '';
                    } else if (item['checked']) {//判断isset 就可以,在ie中，checked的值是空的
                        checked = 'checked="checked"';
                    }
                    temp_html += `<input type="checkbox" name="${item['name']}" value="${item['value']}" ${checked}>${item['value']}&nbsp;`;

                })
                value['name'] = value['parse_name'];
                break;
            case 'select':
                //设置过默认值  清空它  
                if (form_data[value['name']]) {
                    if (value['selected']) {
                        value['content'] = value['content'].replace('selected="selected"', '');
                    }
                    var selected = '';
                    if (form_data[value['name']] == value['value'])
                        selected = 'selected="selected"';
                    //重新定义默认值 
                    value['content'] = value['content'].replace(`value="${value['value']}"`, `value="${value['value']}" ` + selected);
                }
                temp_html = value['content'];
                break;

            case 'macros':
                temp_html = macros_parse(value, form_data[value['name']], controller);
                break;
            case 'progressbar':
                if (controller['action'] == 'edit') {
                    value['value'] = parseFloat(value['value']);
                    value['value'] = value['value'] > 0 ? value['value'] : parseFloat(value['orgvalue']);
                    temp_html = `进度 <input type="text" style="width:40px" name="${value['name']}" value="${value['value']}"/> %`;
                } else if (controller['action'] == 'view') {
                    temp_html = `<div class="progress progress-striped"><div class="bar ${value['orgsigntype']}" style="width: ${value['value']}%;"></div></div>`;
                } else if (controller['action'] == 'preview') {
                    temp_html = `<div class="progress progress-striped"><div class="bar ${value['orgsigntype']}" style="width: ${value['orgvalue']}%;"></div></div>`;
                }

                break;
            case 'qrcode'://未处理生成二维码

                let orgtype = '';
                let qrcode_value = null;
                if (value['orgtype'] == 'text') {
                    orgtype = '文本';
                } else if (value['orgtype'] == 'url') {
                    orgtype = '超链接';
                } else if (value['orgtype'] == 'tel') {
                    orgtype = '电话';
                }
                if (value['value'])
                    qrcode_value = value['value'];
                if (controller['action'] == 'edit') {
                    temp_html = orgtype + `二维码 <input type="text" name="${value['name']}" value="${value['src']}"/>`;
                } else if (controller['action'] == 'view') {
                    //可以采用  http://qrcode.leipi.org/ 

                    var style = '';
                    if (value['orgwidth'] > 0) {
                        style += `width:${value['orgwidth']}px;`;
                    }
                    if (value['orgheight'] > 0) {
                        style += `height:${value['orgheight']}px;`;
                    }
                    temp_html = `<img src="${value['src']}" title="${value['title']}" style="${style}"/>`;


                } else if (controller['action'] == 'preview') {
                    style = '';
                    if (value['orgwidth'] > 0) {
                        style += `width:${value['orgwidth']}px;`;
                    }
                    if (value['orgheight'] > 0) {
                        style += `height:${value['orgheight']}px;`;
                    }
                    temp_html = `<img src="${value['src']}" title="${value['orgtype']}" style="${style}"/>`;
                }

                break;

            case 'listctrl':

                //编辑数据
                let def_value = {}
                def_value[key] = value['value'] ? value['value'] : '';

                var orgtitle = value['orgtitle'].replace(/`$/, '');
                var orgcoltype = value['orgcoltype'].replace(/`$/, '');
                var orgunit = value['orgunit'].replace(/`$/, '');
                var orgsum = value['orgsum'].replace(/`$/, '');
                var orgcolvalue = value['orgcolvalue'].replace(/`$/, '');

                var orgtitle_arr = orgtitle.split('`');
                var orgcoltype_arr = orgcoltype.split('`');
                var orgunit_arr = orgunit.split('`');
                var orgsum_arr = orgsum.split('`');
                var orgcolvalue_arr = orgcolvalue.split('`');

                if (controller['action'] == 'view') {
                    var th_th = '';
                    var tb_td = '';
                    var tf_td = '';
                    var is_sum = 0;
                    var td_sum = 0;
                    orgtitle_arr.forEach((val, k) => {
                        td_sum++;

                        // thead
                        th_th += `<th>${val}</th>`;
                        //tbody
                        tb_td += '<td></td>';

                        //tfooter
                        if (orgsum_arr[k] > 0) {//需要合计
                            tf_td += `<td>合计：0 ${orgunit_arr[k]}</td>`;
                        } else {
                            tf_td += '<td></td>';
                        }

                    })


                    //有编辑值时，还原table
                    var tb_tf_tr = '';//tbody  tfooter
                    if (def_value[key]) {
                        def_value[key]['list'].forEach((dval, dk) => {
                            tb_td = tf_td = '';
                            is_sum = 0;
                            orgtitle_arr.forEach((val, k) => {
                                is_sum++;
                                //tbody
                                tb_td += `<td>${dval[k]} ${orgunit_arr[k]}</td>`;

                                //tfooter
                                if (orgsum_arr[k] > 0) {//需要合计
                                    tf_td += `<td>合计：${def_value[key]['sum'][k]} ${orgunit_arr[k]}</td>`;
                                } else {
                                    tf_td += '<td></td>';
                                }
                            })
                            tb_tf_tr += `<tr>${tb_td}</tr>`;
                        })
                    }

                    temp_html += `<table id="${value['name']}_table" cellspacing="0" class="table table-bordered table-condensed" style="${value['style']}">`;
                    temp_html += `<thead>
                                        <tr><th colspan="${td_sum}">${value['title']}</th></tr>
                                        <tr>${th_th}</tr>
                                        <tr>
                                        </thead>`;

                    if (def_value[key]) {//有编辑值时，还原table
                        temp_html += `<tbody>${tb_tf_tr}</tbody>`;

                    } else {//刚发起的公文，没编辑值时，默认一行
                        temp_html += `<tbody>
                                          <tr class="template">${tb_td}
                                          </tr>
                                        </tbody>`;

                    }
                    if (is_sum > 0) {
                        temp_html += `<tfooter>
                                  <tr>${tf_td}
                                  </tr>
                                </tfooter>`;
                    }

                    temp_html += '</table>';


                } else {//可写
                    temp_html = `<script>
                            function tbAddRow(dname)
                            {
                                var sTbid = dname+"_table";
                                $("#"+sTbid+" .template")  
                                    //连同事件一起复制    
                                    .clone(true)    
                                    //去除模板标记    
                                    .removeClass("template")  
                                    //修改内部元素 
                                    .find(".delrow").removeClass("hide").end()
                                    .find("input").val("").end()
                                    .find("textarea").val("").end()
                                    //插入表格    
                                   .appendTo($("#"+sTbid));
                            }
                            //统计
                            function sum_total(dname,e){
                                
                                var tsum = 0;
                                $(\'input[name="\'+dname+\'[]"]\').each(function(){
                                    var t = parseFloat($(this).val());
                                    if(!t) t=0;
                                    if(t) tsum +=t;
                                    $(this).val(t);
                                }); 
                                $(\'input[name="\'+dname+\'[total]"]\').val(tsum);

                            }

                            /*删除tr*/
                            function fnDeleteRow(obj)
                            {
                                var sTbid = "${value['name']}_table";
                                var oTable = document.getElementById(sTbid);
                                while(obj.tagName !="TR")
                                {
                                    obj = obj.parentNode;
                                }
                                oTable.deleteRow(obj.rowIndex);
                            }
                        </script>`;
                    //print_R(value);exit;

                    th_th = tb_td = tf_td = '';
                    is_sum = 0;
                    td_sum = 0;
                    orgtitle_arr.forEach((val, k) => {
                        td_sum++;

                        //前期
                        var sum_total_html = '';
                        if (orgsum_arr[k] > 0) {//需要合计
                            is_sum++;
                            orgcoltype_arr[k] == 'int';//必须数值
                            sum_total_html = `onblur="sum_total(\'${value['name']}[${k}]\')"`;
                        }

                        // thead
                        th_th += `<th>${val}</th>`;
                        //tbody
                        if (orgcoltype_arr[k] == 'text') {
                            tb_td += `<td><input class="input-medium" type="text" name="${value['name']}[${k}][]" value="${orgcolvalue_arr[k]}"> ${orgunit_arr[k]}</td>`;
                        } else if (orgcoltype_arr[k] == 'textarea') {
                            tb_td += `<td><textarea class="input-medium" name="${value['name']}[${k}][]" >${orgcolvalue_arr[k]}</textarea> ${orgunit_arr[k]}</td>`;
                        } else if (orgcoltype_arr[k] == 'int') {
                            tb_td += `<td><input class="input-medium" ${sum_total_html} type="text" name="${value['name']}[${k}][]" value="${orgcolvalue_arr[k]}"> ${orgunit_arr[k] }</td>`;
                        } else if (orgcoltype_arr[k] == 'calc') {//公式，暂未处理
                            tb_td += `<td><input class="input-medium" type="text" name="${value['name'] }[${k}][]" value="${orgcolvalue_arr[k]}"> ${orgunit_arr[k]}</td>`;
                        }
                        //tfooter
                        if (orgsum_arr[k] > 0) {//需要合计
                            tf_td += `<td>合计：<input type="text" class="input-small" name="${value['name']}[${k}][total]" onblur="sum_total(\'${value['name']}[${k}][]\')" value="${orgcolvalue_arr[k]}"> ${orgunit_arr[k]}</td>`;
                        } else {
                            tf_td += '<td></td>';
                        }

                    })


                    //有编辑值时，还原table
                    tb_tf_tr = '';//tbody  tfooter
                    if (def_value[key]['list']) {
                        def_value[key]['list'].forEach((dval, dk) => {
                            tb_td = tf_td = '';
                            is_sum = 0;
                            orgtitle_arr.forEach((val, k) => {
                                is_sum++;

                                //前期
                                var sum_total_html = '';
                                if (orgsum_arr[k] > 0) {//需要合计
                                    is_sum++;
                                    orgcoltype_arr[k] == 'int';//必须数值
                                    sum_total_html = `onblur="sum_total(\'${value['name']}[${k}]\')"`;
                                }

                                //tbody
                                if (orgcoltype_arr[k] == 'text') {
                                    tb_td += `<td><input class="input-medium" type="text" name="${value['name']}[${k }][]" value="${dval[k]}"> ${orgunit_arr[k]}</td>`;
                                } else if (orgcoltype_arr[k] == 'textarea') {
                                    tb_td += `<td><textarea class="input-medium" name="${value['name']}[${k }][]" >${dval[k]}</textarea> ${orgunit_arr[k]}</td>`;
                                } else if (orgcoltype_arr[k] == 'int') {
                                    tb_td += `<td><input class="input-medium" ${sum_total_html} type="text" name="${value['name']}[${ k}][]" value="${dval[k]}"> ${orgunit_arr[k]}</td>`;
                                } else if (orgcoltype_arr[k] == 'calc') {//公式，暂未处理
                                    tb_td += `<td><input class="input-medium" type="text" name="${value['name']}[${k}][]" value="${dval[k]}"> ${orgunit_arr[k]}</td>`;
                                }
                                //tfooter
                                if (orgsum_arr[k] > 0) {//需要合计
                                    tf_td += `<td>合计：<input type="text" class="input-small" name="${value['name']}[${k}][total]" onblur="sum_total(\'${value['name']}[${k}][]\')" value="${def_value[key]['sum'][k]}"> ${orgunit_arr[k]}</td>`;
                                } else {
                                    tf_td += '<td></td>';
                                }
                            })
                            var delrow_hide = '';
                            var one_tr = '';//作为模板
                            if (dk == 0) {
                                delrow_hide = 'hide';
                                one_tr = 'class="template"';
                            }
                            tb_tf_tr += `<tr ${one_tr}>${tb_td}<td><a href="javascript:void(0);" onclick="fnDeleteRow(this)" class="delrow ${delrow_hide}">删除</a></td></tr>`;
                        })
                    }

                    temp_html += `<table id="${value['name']}_table" cellspacing="0" class="table table-bordered table-condensed" style="${value['style']}">`;
                    temp_html += `<thead>
                                        <tr><th colspan="'+(td_sum+1)+'">
                                        ${value['title']}
                                            <span class="pull-right">
                                                <button class="btn btn-small btn-success" type="button" onclick="tbAddRow(\'${value['name']}\')">添加一行</button>
                                            </span>
                                        </th></tr>
                                        <tr>
                                          <tr>${th_th}<th>操作</th></tr>
                                        </thead>`;

                    if (def_value[key]['list']) {//有编辑值时，还原table
                        temp_html += `<tbody><tr></tr>${tb_tf_tr}</tbody>`;

                    } else {//刚发起的公文，没编辑值时，默认一行
                        temp_html += `
                                          <tr class="template">${tb_td}
                                            <td><a href="javascript:void(0);" onclick="fnDeleteRow(this)" class="delrow hide">删除</a></td>
                                          </tr>
                                        </tbody>`;

                    }
                    if (is_sum > 0) {
                        temp_html += `<tfooter>
                                  <tr>${tf_td}
                                    <td></td>
                                  </tr>
                                </tfooter>`;
                    }

                    temp_html += '</table>';

                }//可写
                break;
            default:
                temp_html = value['content'];
        }
        if (value['name'])
            tpl = tpl.replace(`{${value['name']}}`, temp_html);
    })
    return tpl;
}


function macros_parse(data, def_value = '', controller) {
    var tpl = data['content'];
    var date_format = '';
    switch (data['orgtype']) {
        case 'sys_date':
            date_format = 'YYYY-MM-DD'; break;
        case 'sys_date_cn':
            date_format = 'YYYY年MM月DD日'; break;
        case 'sys_date_cn_short3':
            date_format = 'YYYY年'; break;
        case 'sys_date_cn_short4':
            date_format = 'YYYY'; break;
        case 'sys_date_cn_short1':
            date_format = 'YYYY年MM月'; break;
        case 'sys_date_cn_short2':
            date_format = 'MM月DD日'; break;
        case 'sys_time':
            date_format = 'HH:mm:ss'; break;
        case 'sys_datetime':
            date_format = 'YYYY-MM-DD HH:mm:ss'; break;
        case 'sys_week'://周
            if (!def_value) {
                var dateArray  =   new Date(date);
                var wday = dateArray["wday"];
                var week = Array.from("日", "一", "二", "三", "四", "五", "六");
                def_value = '星期'+week[wday];
            }
            tpl = tpl.replace('{macros}', def_value);
            break;
        case 'sys_userid':
            if (!def_value)
                def_value = controller['user']['uid'];
            tpl = tpl.replace('{macros}', def_value);
            break;
        case 'sys_realname':
            if (!def_value)
                def_value = controller['user']['real_name'];
            tpl = tpl.replace('{macros}', def_value);
            break;
        default:
            tpl = tpl.replace('{macros}', '未完善的宏控件');
            break;
    }
    //时间
    if (date_format) {
        def_value = def_value.replace('年', '-');
        def_value = def_value.replace('月', '-');
        def_value = def_value.replace('日', '');
        def_value = def_value.replace(/-$/, '');

        var timestamp = 0;
        if (def_value) {
            if(def_value.length == 4) {
                def_value += '-01';
            }
            timestamp = new Date(def_value).getTime();
           
        } else {
            timestamp = new Date().getTime();
        }
        
        if (!timestamp) {
            tpl = tpl.replace('{macros}', def_value);//时间转换失败时
        } else {
            tpl = tpl.replace('{macros}', format(new Date(), date_format, {locale}));
        }
    }

    return tpl;
    
}

// generate data from post data
function unparse_data(form, post_data) {
    var tpl_data = form['content_data'];

    var return_data = {};
    tpl_data.forEach((value, key) => {
        switch (value['leipiplugins']) {
            //不同的类型，可以加入不同的处理方式

            case 'checkboxs'://包含多个 name
                value['options'].forEach((val) => {
                    return_data[val['name']] = post_data[val['name']] ? 1 : 0;
                    //return_data[val['name']]= post_data[val['name']] ? trim(post_data[val['name']]) : '';
                })
                break;
            /*case 'qrcode'://生成二维码
                //可以采用  http://qrcode.leipi.org/ 
                qrcode_url = '';
                
                qrcode = post_data[value['name']] ? trim(post_data[value['name']]) : '';
                if(qrcode)
                {
                    import('@.Org.QRcode');//import 为Thinkphp内置，使用其它框架请换成： include_once     
                    qrcode_file = 'Uploads/'.md5(qrcode).'.png';
                    qrcode_url = '/'.qrcode_file;
                    qrcode_path = SITE_DIR.qrcode_file;
                    
                    size = Math.round(value['orgwidth']/25);//QRcode size计算
                    if(size<=0) size =1;
                    if(value['orgtype']=='text')
                    {
                        \QRcode::png(qrcode, qrcode_path, 'L',size, 2);
                    }else if(value['orgtype']=='url')
                    {
                        \QRcode::png('url:'.qrcode, qrcode_path, 'L',size, 2);
                    }else if(value['orgtype']=='tel')
                    {
                        \QRcode::png('tel:'.qrcode, qrcode_path, 'L',size, 2);
                    }else
                    {
                        qrcode_url = '';
                    }
                    
                }
                return_data[value['name']] =serialize(array(
                        'value'=>qrcode,
                        'qrcode_url'=>qrcode_url,
                    ));
                break;*/
            case 'listctrl':

                if (!post_data[value['name']][0]) {
                    return_data[value['name']] = '';
                    break;
                }

                var temparr = [];
                //处理用户输入 


                var orgcoltype = value['orgcoltype'].replace(/`$/, '');
                var orgsum = value['orgsum'].replace(/`$/, '');

                var orgcoltype_arr = orgcoltype.split('`');
                var orgsum_arr = orgsum.split('`');

                var temparr_sum = [];//合计
                post_data[value['name']][0].forEach((val, k) => {
                    temparr[k] = [];
                    //if(val=='') continue;

                    post_data[value['name']].forEach((val2, k2) => {
                        if (orgcoltype_arr[k2] == 'int') {
                            temparr[k][k2] = parseFloat(post_data[value['name']][k2][k]);
                        } else {
                            temparr[k][k2] = post_data[value['name']][k2][k];
                        }

                        //合计
                        if (orgsum_arr[k2] > 0) {
                            temparr_sum[k2] = post_data[value['name']][k2]['total'];
                        }
                    })

                })

                return_data[value['name']] = {
                    'list': temparr,   //行数据
                    'sum': temparr_sum,//合计
                }
                break;
            case 'text':
            case 'textarea':
            case 'radios':
            case 'select':
            case 'macros':
            case 'progressbar':
            default:
                return_data[value['name']] = post_data[value['name']] ? post_data[value['name']] : '';
        }

    })
    return return_data;
}

function convertData(form, post_data) {
    var tpl_data = form['content_data'];

    var return_data = {};
    tpl_data.forEach((value, key) => {
        switch (value['leipiplugins']) {
            case 'listctrl':
                var orgcoltype = value['orgcoltype'].replace(/`$/, '');
                var orgsum = value['orgsum'].replace(/`$/, '');

                var orgcoltype_arr = orgcoltype.split('`');
                var orgsum_arr = orgsum.split('`');

                let cols = orgcoltype_arr.length;
                let fieldData = [];
                for (let i = 0; i < cols; i++) {
                    let fieldName = value['name'] + `[${i}][]`;
                    if (Array.isArray(post_data[fieldName])) {
                        fieldData[i] = post_data[fieldName];
                    } else {
                        fieldData[i] = [post_data[fieldName]];
                    }
                    delete post_data[fieldName];
                    if (orgsum_arr[i] > 0) {
                        let totalFieldName = value['name'] + `[${i}][total]`;
                        fieldData[i]['total'] = post_data[totalFieldName];
                        delete post_data[totalFieldName];
                    }
                }
                post_data[value['name']] = fieldData;
                break;
        }
    })
}

module.exports = { parse_form, unparse_form, unparse_data, convertData }
